package cn.ww.service;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import cn.ww.po.MyResponse;
import cn.ww.po.User;
import cn.ww.util.TokenUtils;

@Service
public class SysUserService {
    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private TokenUtils tokenUtils;


    /** 用户登录
     * @param sysUser 用户登录信息
     * @return 用户登录成功返回的Token
     */
    public MyResponse login(final User sysUser) {
        try {
            // 验证用户名和密码是否对的
            System.out.println(sysUser.getUsername());
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(sysUser.getUsername(),
                            sysUser.getPassword()));
        } catch (BadCredentialsException e) {
            return new MyResponse("ERROR", "用户名或者密码不正确");
        }
        // 生成Token与查询用户权限
        User user = new User();
        if ("aaa".equals(sysUser.getUsername())) {
            user.setUsername("aaa");
            user.setPassword("123");
            user.setRoles("ROLE_USER");
        }else if("bbb".equals(sysUser.getUsername())){
            user.setUsername("bbb");
            user.setPassword("123");
            user.setRoles("ROLE_ADMIN");
        }
        return new MyResponse("SUCCESS", tokenUtils.createToken(user));
    }
}
